﻿using System;
using System.Collections.Generic;

using agsXMPP.protocol.iq.roster;

using VSTalk.Engine.Core.XmppUtils;
using VSTalk.Model;

namespace VSTalk.Engine.Core.XmppConnection.RosterObserver
{
    public class RosterListHandler
    {
        private readonly Client _client;

        private readonly IDictionary<string, Interlocutor> _interlocutors = new Dictionary<string, Interlocutor>();

        public RosterListHandler(Client client)
        {
            _client = client;
        }

        public void Start()
        {
            foreach (var interlocutor in _client.Contacts)
            {
                var bare = XmppIdConverter.Jid(interlocutor).ToString().ToLower();
                _interlocutors.Add(bare, interlocutor);
            }
        }

        public void Stop()
        {
            foreach (var interlocutor in _interlocutors.Values)
            {
                _client.Contacts.Remove(interlocutor);
            }
            _interlocutors.Clear();
        }

        public void OnRoster(RosterItem item)
        {
            var bare = item.Jid.Bare.ToLower();
            if (!_interlocutors.ContainsKey(bare) && item.Subscription != SubscriptionType.remove)
            {
                bool subscribed = RosterData.Subscribed(item);
                var jid = item.Jid;
                var name = RosterData.Name(item);
                var interlocutor = new Interlocutor
                {
                    Id = Guid.NewGuid(),
                    Name = name,
                    Server = jid.Server,
                    User = jid.User,
                    Subscribed = subscribed,
                };
                _client.Contacts.Add(interlocutor);
            }
            else if (_interlocutors.ContainsKey(bare) && item.Subscription != SubscriptionType.remove)
            {
                bool subscribed = RosterData.Subscribed(item);
                var jid = item.Jid;
                var name = RosterData.Name(item);
                var interlocutor = _interlocutors[bare];
                interlocutor.Name = name;
                interlocutor.Server = jid.Server;
                interlocutor.User = jid.User;
                interlocutor.Subscribed = subscribed;
                _interlocutors.Remove(bare);
            }
            else if (_interlocutors.ContainsKey(bare) && item.Subscription == SubscriptionType.remove)
            {
                var interlocutor = _interlocutors[bare];
                _interlocutors.Remove(bare);
                _client.Contacts.Remove(interlocutor);
            }
        }
    }
}